package com.atguigu.auth.service.impl;

import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.model.system.SysUser;

import com.atguigu.security.custom.CustomUser;
import com.atguigu.security.custom.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * ClassName: UserDetailsServiceImpl
 * Package: com.atguigu.auth.service.impl
 *
 * @Author: lmf
 * @Create: 2024/1/21 11:24
 * @Version: 1.0
 * Description:  根据用户名称进行查询
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserService userService;
    private final SysMenuService menuService;

    public UserDetailsServiceImpl(SysUserService userService, SysMenuService menuService) {
        this.userService = userService;
        this.menuService = menuService;
    }
    /**
     * 根据用户名进行查询
     * @param username 用户名称
     * @return 用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名进行查询
        final SysUser user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
//        System.out.println(Collections.emptyList()+"Collections.emptyList()");
        // 根据用户id 查询用户操作权限
        final List<String> permsByUserId = menuService.findUserPermsByUserId(user.getId());
        // 创建list 集合封装最终权限数据
        final ArrayList<SimpleGrantedAuthority> authList = new ArrayList<>();
        // 查询list集合遍历
        for (String perm : permsByUserId) {
            authList.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(user, authList);
    }
}
